package band.wukong.practice.netty.userguide.heartbeat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Desc:
 * author: wukonggg@139.com
 */
public class HeartbeatServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LogManager.getLogger();

    // Return a unreleasable view on the given ByteBuf which will just ignore release and retain calls.
    // 定义了心跳时，要发送的内容
    private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(
            Unpooled.copiedBuffer("Heartbeat", CharsetUtil.UTF_8));

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        // 判断是否是 IdleStateEvent 事件，是则处理
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            if (event.state() == IdleState.READER_IDLE) {
                type = "read idle";
            } else if (event.state() == IdleState.WRITER_IDLE) {
                type = "write idle";
            } else if (event.state() == IdleState.ALL_IDLE) {
                type = "all idle";
            }

            ChannelFuture f = ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate());
            f.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

            logger.info(ctx.channel().remoteAddress() + "超时类型：" + type);

        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
